package com.yami.shop.api.controller;


import cn.hutool.json.JSONObject;
import com.yami.shop.bean.model.Product;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.SendMessageToUserService;
import com.yami.shop.service.UserService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class WXcode {
    @Autowired
    private SendMessageToUserService sendMessageToUserService;
    @Autowired
    private UserService userService;


    @PostMapping("/getWxCode")
    public ResponseEntity<String> getWxCode(@RequestBody Product product){
        String userId = SecurityUtils.getUser().getUserId();
        //获取appConnectId
        Long appConnectId = userService.getAppConnectId(userId);
        String accesstoken =sendMessageToUserService.getToken("wx77577c20c1aa61b1","d3cd926f87052ac422a765a2c891d549");
        StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=");
        requestUrl.append(accesstoken);
        JSONObject json = new JSONObject();
        json.put("page", "pages/prod/prod");
        json.put("width", "200");
        json.put("scene", product.getProdId()+"-"+product.getShopId()+"-"+appConnectId);
        Map<String, Object> map = null;
        String result1 = "";
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpPost post = new HttpPost(requestUrl.toString());//构建一个POST请求
            StringEntity s = new StringEntity(json.toString(), "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json; charset=UTF-8");
            //s.setContentType("image/png");
            post.setEntity(s);//设置编码，不然模板内容会乱码
            HttpResponse response = client.execute(post);//提交POST请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            InputStream inputStream = response.getEntity().getContent();
            // 将获取流转为base64格式
            byte[] data = null;
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
            result1 = new String(Base64.getEncoder().encode(data));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(result1);
    }

    /**
     * 获取海报小程序码
     * @param product
     * @return
     */
    @PostMapping("/getPosterWxCode")
    public ResponseEntity<String> getPosterWxCode(@RequestBody Product product){
        String userId = SecurityUtils.getUser().getUserId();
        //获取appConnectId
        Long appConnectId = userService.getAppConnectId(userId);
        String accesstoken =sendMessageToUserService.getToken("wx77577c20c1aa61b1","d3cd926f87052ac422a765a2c891d549");
        StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=");
        requestUrl.append(accesstoken);
        JSONObject json = new JSONObject();
        json.put("page", "pages/home/home");
        json.put("width", "200");
        json.put("scene", appConnectId);
        Map<String, Object> map = null;
        String result1 = "";
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpPost post = new HttpPost(requestUrl.toString());//构建一个POST请求
            StringEntity s = new StringEntity(json.toString(), "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json; charset=UTF-8");
            //s.setContentType("image/png");
            post.setEntity(s);//设置编码，不然模板内容会乱码
            HttpResponse response = client.execute(post);//提交POST请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            InputStream inputStream = response.getEntity().getContent();
            // 将获取流转为base64格式
            byte[] data = null;
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
            result1 = new String(Base64.getEncoder().encode(data));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(result1);
    }

    /**
     * 获取转盘小程序码
     */
    @GetMapping("/getLuckProdCode")
    public ResponseEntity<String> getLuckProdCode(){
        String accesstoken =sendMessageToUserService.getToken("wx77577c20c1aa61b1","d3cd926f87052ac422a765a2c891d549");
        StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=");
        requestUrl.append(accesstoken);
        JSONObject json = new JSONObject();
        json.put("page", "pages/luckProd/luckProd");
        json.put("width", "200");
        json.put("scene", "111");
        Map<String, Object> map = null;
        String result1 = "";
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpPost post = new HttpPost(requestUrl.toString());//构建一个POST请求
            StringEntity s = new StringEntity(json.toString(), "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json; charset=UTF-8");
            //s.setContentType("image/png");
            post.setEntity(s);//设置编码，不然模板内容会乱码
            HttpResponse response = client.execute(post);//提交POST请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            InputStream inputStream = response.getEntity().getContent();
            // 将获取流转为base64格式
            byte[] data = null;
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
            result1 = new String(Base64.getEncoder().encode(data));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(result1);
    }

    /**
     * 获取拼团小程序二维码
     */
    @GetMapping("/getPtWxCode")
    public ResponseEntity<String> getPtWxCode(Long ptglid,Long prodId,Long shopId){
        String accesstoken =sendMessageToUserService.getToken("wx77577c20c1aa61b1","d3cd926f87052ac422a765a2c891d549");
        StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=");
        requestUrl.append(accesstoken);
        JSONObject json = new JSONObject();
        json.put("page", "pages/groupbuy/groupbuy");
        json.put("width", "200");
        json.put("scene", ptglid+"-"+prodId+"-"+shopId);
        Map<String, Object> map = null;
        String result1 = "";
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpPost post = new HttpPost(requestUrl.toString());//构建一个POST请求
            StringEntity s = new StringEntity(json.toString(), "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json; charset=UTF-8");
            //s.setContentType("image/png");
            post.setEntity(s);//设置编码，不然模板内容会乱码
            HttpResponse response = client.execute(post);//提交POST请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            InputStream inputStream = response.getEntity().getContent();
            // 将获取流转为base64格式
            byte[] data = null;
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
            result1 = new String(Base64.getEncoder().encode(data));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(result1);
    }

    /**
     * 进入会员注册页面
     */
    @GetMapping("/enterMemberPage")
    public  ResponseEntity<String> enterMemberPage(){
        String accesstoken =sendMessageToUserService.getToken("wx77577c20c1aa61b1","d3cd926f87052ac422a765a2c891d549");
        StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=");
        requestUrl.append(accesstoken);
        JSONObject json = new JSONObject();
        json.put("page", "pages/member/member-registe");
        json.put("width", "200");
        json.put("scene", "111");
        Map<String, Object> map = null;
        String result1 = "";
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpPost post = new HttpPost(requestUrl.toString());//构建一个POST请求
            StringEntity s = new StringEntity(json.toString(), "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json; charset=UTF-8");
            //s.setContentType("image/png");
            post.setEntity(s);//设置编码，不然模板内容会乱码
            HttpResponse response = client.execute(post);//提交POST请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            InputStream inputStream = response.getEntity().getContent();
            // 将获取流转为base64格式
            byte[] data = null;
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
            result1 = new String(Base64.getEncoder().encode(data));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(result1);
    }






}
